package org.shaka.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;

public class StringIOComponent {
    public static interface StringResource extends Iterator<String>, Iterable<String> {
        public void start();

        public void start(String encoding);

        public boolean hasNext();

        public String next();
    }

    public static interface StringTarget {
        public void output(String output);

        public void flush();
    }

    public static class EachLineStringResource implements StringResource {
        private InputStream in;
        private BufferedReader reader;
        private String currentLine;

        public EachLineStringResource(InputStream in) {
            this.in = in;
        }

        @Override
        public void start() {
            this.reader = new BufferedReader(new InputStreamReader(in));
        }

        @Override
        public void start(String encoding) {
            try {
                this.reader = new BufferedReader(new InputStreamReader(in, encoding));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public boolean hasNext() {
            try {
                return (currentLine = reader.readLine()) != null;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public String next() {
            return currentLine;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<String> iterator() {
            if (reader == null)
                throw new RuntimeException("not start with encoding ...");
            return this;
        }
    }
}
